<template class="firstpage">
  <div>
    <div class="boxMargin" style="margin: 20px 0;">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="demo-ruleForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品分类：" required>
              <!-- prop="categoryId" -->
              <div style="display:inline-block;">
                <el-select v-for="(arrItem,key) in customData.categroyList" :key="key" v-model="customData.selectArr[key]" style="margin-right:10px;" @focus="customData.position=key" @change="handleItemChange">
                  <el-option v-for="item in arrItem" :key="item.categoryId" :value="item.categoryId" :label="item.categoryName" />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="货号：" prop="skuCode">
              <el-input v-model="form.skuCode" class="w70" :disabled="customData.skuCodeIsShow" />
              <el-button type="primary" size="small" style="display:inline-block" @click="onCopy">复制商品</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品条码：" prop="upCode">
              <!-- <el-input @input="hostUpcChange($event)" type="textarea" :rows="3" v-model="customData.hostUpc" placeholder="支持多Hostupc输入，以回车换行分割" class="w70"></el-input> -->
              <el-input v-model="form.upCode" class="w70" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品名称：" prop="goodsName">
              <el-input v-model="form.goodsName" class="w70" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品副标题：">
              <el-input v-model="form.goodsSubtitle" class="w70" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品简称：">
              <el-input v-model="form.goodsSname" class="w70" />
            </el-form-item>
          </el-col>
          <el-col :span="10" style="display:flex">
            <el-form-item label="品牌：" prop="brandId">
              <el-select v-model="form.brandId" placeholder="请选择" filterable remote reserve-keyword :remote-method="brandNameChange" :loading="customData.loading">
                <el-option v-for="item in customData.brandNameList" :key="item.brandId" :label="item.brandName" :value="item.brandId" />
              </el-select>
            </el-form-item>&nbsp;&nbsp;&nbsp;
            <el-checkbox v-model="customData.checked" style="margin-top:10px">前端不显示</el-checkbox>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="配送温度：">
              <el-select v-model="form.keepTemperature" placeholder="请选择" clearable>
                <el-option v-for="item in customData.keepTemperatureList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="宽：" prop="widthNum">
              <el-input v-model="form.widthNum" class="w70" type="number">
                <template slot="append">mm</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="高：" prop="heightNum">
              <el-input v-model="form.heightNum" class="w70" type="number">
                <template slot="append">mm</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="深：" prop="lengthNum">
              <el-input v-model="form.lengthNum" class="w70" type="number">
                <template slot="append">mm</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品重量：" prop="weightNum">
              <el-input v-model="form.weightNum" class="w70" type="number">
                <template slot="append">KG</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-form-item>
              <el-button type="success" @click="infoUpdate('form')">保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-dialog title="复制商品" :visible.sync="dialogData.isCopy" width="30%" center>
      <el-form label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="hostitem" required>
              <el-input v-model="customData.copyNum" type="text" placeholder="请填写需要复制的商品hostitem" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top:10px"><el-col :span="24">确定复制后，除商品的“hostitem”、“hostUPC”以外的其他商品信息均覆盖当前商品！</el-col></el-row>
        <el-row style="text-align: right;margin-top:20px;">
          <el-button type="primary" size="small" @click="onSure">确定复制</el-button>
          <el-button plain size="small" @click="dialogData.isCopy=false;customData.copyNum=''">取消</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import $ from 'jquery'
import _validate from '../../../../../framework/commonJs/wptx_validate'
import _tools from '../../../../../framework/commonJs/wptx_tools'
import _common from '../../../../../framework/commonJs/wptx_common'
import _allApi from '../../../../../framework/API/apiAll'
import _api from '../../../../../framework/API/generalItem'
const _FUNCTION_NAME = ''
export default {
  filters: {},
  data() {
    return {
      tableData: [],
      searchData: {
      },
      searchDataBuffer: {
      },
      pageData: {
        pageNo: 1,
        pageSize: 10,
        total: 1,
        pageSizes: [10, 20, 50, 100]
      },
      dialogData: { isCopy: false },
      historyData: {},
      infoData: {},
      customData: {
        brandNameList: [],
        keepTemperatureList: [
          { label: '请选择', value: '' },
          { label: '冷藏(0-4℃)', value: '0' },
          { label: '常温', value: '1' },
          { label: '急冻(-18℃)', value: '2' }
        ],
        loading: false,
        categroyList: [],
        parentId: '',
        selectArr: [],
        position: null,
        versionId: '',
        itemId: '',
        categoryListType: '',
        hostUpc: '',
        copyNum: '',
        checked: false,
        isVal: false,
        skuCodeIsShow: false
      },
      form: {
      },
      rules: {
        skuCode: [
          { required: true, validator: (rule, value, callback) => {
            const reg = new RegExp('^[0-9]*$')
            if (_validate.checkEmpty(value)) {
              this.customData.isVal = false
              return callback(new Error('请输入HostItem'))
            } else {
              if (!reg.test(value)) {
                this.customData.isVal = false
                return callback(new Error('只能输入数字'))
              }
            }
            callback()
          }, trigger: 'blur' }
        ],
        upCode: [
          { required: true, validator: (rule, value, callback) => {
            const reg = new RegExp('^[0-9]*$')
            if (_validate.checkEmpty(value)) {
              return callback(new Error('请输入upCode'))
            } else {
              if (!reg.test(value)) {
                return callback(new Error('只能输入数字'))
              }
            }
            callback()
          }, trigger: 'blur' }
        ],
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        brandId: [
          { required: true, message: '请选择品牌', trigger: 'change' }
        ],
        widthNum: [
          { required: true, message: '请输入宽', trigger: 'blur' }
        ],
        heightNum: [
          { required: true, message: '请输入高', trigger: 'blur' }
        ],
        lengthNum: [
          { required: true, message: '请输入深', trigger: 'blur' }
        ],
        weightNum: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        isPrecious: [
          { required: true, message: '请选择是否贵重物品', trigger: 'change' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() { },
  mounted() {
    this._FUNCTION_NAME = this.$route.name
    this.onInit()
  },
  beforeDestroy() { },
  methods: {
    blurFn(val) {
      if (!_validate.checkEmpty(val)) {
        this.customData.isVal = false
      } else {
        this.customData.isVal = false
      }
    },
    onInit() {
      const self = this
      self.customData.itemId = self.$route.query.itemId
      self.customData.itemVersionId = self.$route.query.itemVersionId
      const params = {
        itemId: self.customData.itemId,
        itemVersionId: self.customData.itemVersionId
      }
      _api.infoDetail(self, params, self.callBack_infoDetail)
    },
    onSearch(data) {
      const self = this
    },
    onChangePage(data) {
      const self = this
      const params = {
        itemId: self.customData.itemId,
        itemVersionId: self.customData.itemVersionId
      }
      _api.infoDetail(self, params, self.callBack_infoDetail)
    },
    onReset(data) {
      const self = this
    },
    onAdd(data) { },
    onDelete(data) {
      const self = this
    },
    onInfo(data) {
      const self = this
    },
    onUpdate(formName) {
      const self = this
    },
    onBathDelete() {
      const self = this
    },
    onBathUpdate() { },
    onDisable(data) {
      const self = this
    },
    onEnable(data) {
      const self = this
    },
    onUpload(data) { },
    onBathUpload() { },
    onExport(data) { },
    onDownload(data) { },
    onHistory(data) { },
    onSure() {
      const self = this; const params = { skuCode: '', masterItemId: '' }
      if (_validate.checkKong(self.customData.copyNum)) {
        _validate.openTip(self, 'hostitem不可为空', 'warning')
        return false
      } else {
        params.skuCode = self.customData.copyNum
        params.masterItemId = self.customData.itemId
        _api.itemOneCopy(self, params, self.callBack_itemOneCopy)
      }
    },
    // 详情
    callBack_infoDetail(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '详情数据加载超时，请刷新页面后重试', 'warning')
      } else {
        self.form = data.data
        if (data.data.brandIsShow == 0) {
          self.customData.checked = true
        } else {
          self.customData.checked = false
        }
        if (_validate.checkEmpty(data.data.skuCode)) {
          self.customData.skuCodeIsShow = false
        } else {
          self.customData.skuCodeIsShow = true
        }
        self.$emit('func', data.data)
        sessionStorage.setItem('categoryId', data.data.categoryId)
        self.previewCategory(data.data.categoryIds, data.data.categoryNames) // 去请求分类
        if (!_validate.checkEmpty(data.data.brandId)) {
          self.brandNameChange(data.data.brandName)
        }
        if (data.data.categoryIsLeaf == 0) {
          _allApi.categroyCascade(self, { parentId: data.data.categoryId }, self.callBack_initCategoryCascade, data.data.categoryIds, Number(data.data.categoryLevel))
        }
        self.customData.hostUpc = _tools.commaTo(self.form.upCode)
      }
    },
    callBack_infoUpdate(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '更新超时，请稍后重试', 'warning')
      } else {
        _validate.openTip(self, '修改成功', 'success')
        sessionStorage.setItem('categoryId', self.form.categoryId)
        self.customData.skuCodeIsShow = true
      }
    },
    callBack_brandSelect(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '品牌数据加载超时，请刷新页面后重试', 'warning')
      } else {
        self.customData.loading = false
        self.customData.brandNameList = data.data.result
      }
    },
    callBack_itemOneCopy(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '复制数据加载超时，请刷新页面后重试', 'warning')
      } else {
        self.dialogData.isCopy = false
        self.customData.copyNum = ''
        const routeUrl = self.$router.resolve({
          path: '/samUpdate',
          query: {
            itemId: data.data.data.masterItemId,
            itemVersionId: data.data.data.itemVersionId,
            productType: data.data.data.productType
          }
        })
        window.close()
        window.open(routeUrl.href)
      }
    },
    callBack_initCategoryCascade(data, idList, index) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '分类数据加载超时，请刷新页面后重试', 'warning')
      } else {
        if (_validate.checkEmpty(index)) {
          // 仅处理一级分类
          _tools.info('-->仅处理一级分类')
          self.customData.categroyList = []
          self.customData.categroyList.push(data.data)
          self.customData.selectArr = []
          return
        } else {
          if (_validate.checkListEmpty(idList)) {
            _tools.info('-->处理[' + index + ']级分类')
            // 处理对应级别分类
            if (index == 0 || data.data.length != 0) {
              self.customData.categroyList.splice(index + 1, self.customData.categroyList.length, data.data)
              self.customData.selectArr.splice(index + 1, self.customData.selectArr.length)
            }
            if (data.data.length == 0) {
              self.customData.categroyList.splice(index + 1, self.customData.categroyList.length)
              self.customData.selectArr.splice(index + 1, self.customData.selectArr.length)
            }
          } else {
            _tools.info('-->级联处理[' + index + ']级分类')
            self.customData.categroyList[index] = data.data // 将刚刚的默认渲染的一条数据所对应的位置 换成 后台给的数据
            index++
            if (index >= idList.length) { // 当 处理到最后一级时  直接退出
              return
            }
            const currId = idList[index - 1]
            self.initCategoryList(idList, currId, index)
          }
        }
      }
    },
    brandNameChange(query) {
      const self = this
      if (!_tools.blankSpace(query)) {
        self.customData.loading = true
        const params = {
          brandName: query
        }
        setTimeout(function() {
          _allApi.brandSelect(self, params, self.callBack_brandSelect)
        }, 1000)
      } else {
        self.customData.brandNameList = []
      }
    },
    handleItemChange(e) {
      const self = this
      const current = e// 获取选中值(实际项目可通过此值调接口获取下一级选项)
      self.form.categoryId = current
      self.initCategoryList(null, current, self.customData.position)
    },
    infoUpdate(formName) {
      const self = this
      if (_validate.checkEmpty(self.form.categoryId)) {
        _validate.openTip(self, '请选择商品分类', 'warning')
        return
      }
      const params = self.form
      params.itemId = self.customData.itemId
      for (let i = 0; i < self.customData.brandNameList.length; i++) {
        if (self.customData.brandNameList[i].brandId == self.form.brandId) {
          params.brandName = self.customData.brandNameList[i].brandName
        }
      }
      self.$refs[formName].validate((valid) => {
        if (valid) {
          if (self.customData.checked == true) {
            params.brandIsShow = 0
          } else {
            params.brandIsShow = 1
          }
          _api.infoUpdate(self, params, self.callBack_infoUpdate)
        } else {
          return false
        }
      })
    },
    hostUpcChange(value) {
      const self = this
      self.customData.hostUpc = self.customData.hostUpc.replace(/[^\r\n0-9]/g, '')
      self.form.upCode = _tools.enter(self.customData.hostUpc)
    },
    previewCategory(idList, nameList) {
      const self = this
      if (_validate.checkListEmpty(idList)) {
        // 未选择一级分类，初始化一级分类，且设置成请选择
        self.initCategoryList()
      } else {
        if (idList.length != nameList.length) {
          // id与name长度不等 只请求一级分类 并设置成已选择
          self.initCategoryList()
        } else {
          // 已选择一级分类，还原现有分类
          self.customData.selectArr = idList
          // 默认将 已选的分类展示出来 以防后台给的数据有问题
          self.initPreviewCategoryList(idList, nameList)
          // 级联查询 传index为0 下标开始
          self.initCategoryList(idList, '', 0)
        }
      }
    },
    initPreviewCategoryList(idList, nameList) {
      const self = this
      let currId
      let currName
      let parentId
      let isLeaf
      for (let cnt = 0; cnt < idList.length; cnt++) {
        currId = idList[cnt]
        currName = nameList[cnt]
        if (cnt == 0) {
          parentId = ''
        } else {
          parentId = idList[cnt - 1]
        }
        if (cnt == idList.length - 1) {
          isLeaf = 1
        } else {
          isLeaf = 0
        }
        const categoryInfo = {
          'categoryId': currId,
          'categoryName': currName,
          'parentId': parentId,
          'isLeaf': isLeaf,
          'categoryLevel': (cnt + 1)
        }
        const categoryList = []
        categoryList.push(categoryInfo)
        self.customData.categroyList.push(categoryList)
      }
    },
    initCategoryList(idList, currId, index) {
      const self = this
      const data = {
        parentId: currId
      }
      _allApi.categroyCascade(self, data, self.callBack_initCategoryCascade, idList, index)
    },
    onCopy() {
      const self = this
      self.dialogData.isCopy = true
    }
  }
}
</script>
<style scoped>
.w70{
    width: 70%;
}
</style>
